import React, { Component, PropTypes } from 'react';
import DataTable from '../../DataTable'
import TreeLikeUI from '../../TreeLikeUI'
import ajax from '../../../ajax'

class Role extends Component {

  constructor () {

    super()

    this.state = {
      tableConfig: {
        columns: [{
          title: '角色名称',
          name: 'roleName'
        }, {
          title: '角色描述',
          name: 'roleDesc'
        }, {
          title: '是否可用',
          name: 'roleStatus',
          type: 'boolean'
        }, {
          command: [{
            name: 'create'
          }, {
            name: 'edit',
            text: '编辑'
          }, {
            name: 'delete',
            text: '删除'
          }, {
            name: 'resConfig',
            text: '资源配置'
          }]
        }],
        transport: {
          read: {
            url: '/api/role/getPagination',
            parse: () => {}
          },
          create: '/api/role/add',
          update: {
            url: '/api/role/edit',
            format: () => {}
          },
          destroy: '/api/role/del'
        }
      }
    }
  }

  static contextTypes = {
    onSetTitle: PropTypes.func.isRequired,
  }

  render() {
    this.context.onSetTitle('角色管理')

    return (
      <div>
        <DataTable config={this.state.tableConfig} onModalBodyInit={this._onModalBodyInit.bind(this)} onSubmit={this._onSubmit.bind(this)}/>
      </div>
    )
  }

  _onModalBodyInit (type) {
    if (type === 'resConfig')
    return (
      <div  id='resConfig'>
        <TreeLikeUI data={'/api/resources/tree?resourcesType=ALL'} checkable={true}/>
      </div>
    )
  }

  _onSubmit (data, callback) {
    let _resourcesIds = [];
    $('#resConfig .tree-node-ckb:checked').each(function(i,e){
      _resourcesIds.push($(e).attr('data-id'))
    })
    if(_resourcesIds.length>0){
      data.resourcesIds=_resourcesIds.join(',')
    }
    return ajax({
      url: '/api/role/edit',
      data: data,
      success: resp => {
        console.log(resp)
        if (resp && 0 === resp.code) {
          callback(true)
        }
      }
    })
  }

}

export default Role
